/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.fenRecordLog.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.fenRecordLog.domain.FenRecordLog;
import com.fzhucc.modules.fenType.domain.FenType;
import com.fzhucc.modules.fenType.repository.FenTypeRepository;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.fenRecordLog.repository.FenRecordLogRepository;
import com.fzhucc.modules.fenRecordLog.domain.dto.FenRecordLogDto;
import com.fzhucc.modules.fenRecordLog.domain.dto.FenRecordLogQueryCriteria;
import com.fzhucc.modules.fenRecordLog.service.mapstruct.FenRecordLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-06-05
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class FenRecordLogService {

    private final FenRecordLogRepository fenRecordLogRepository;

    private final FenTypeRepository fenTypeRepository;
    private final FenRecordLogMapper fenRecordLogMapper;

    private final UserService userService;

    private final UserRepository userRepository;

    public Map<String, Object> queryAll(FenRecordLogQueryCriteria criteria, Pageable pageable) {
        Page<FenRecordLog> page = fenRecordLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(fenRecordLogMapper::toDto));
    }

    public List<FenRecordLogDto> queryAll(FenRecordLogQueryCriteria criteria) {
        return fenRecordLogMapper.toDto(fenRecordLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public FenRecordLogDto findById(Integer id) {
        FenRecordLog fenRecordLog = fenRecordLogRepository.findById(id).orElseGet(FenRecordLog::new);
        ValidationUtil.isNull(fenRecordLog.getId(), "FenRecordLog", "id", id);
        return fenRecordLogMapper.toDto(fenRecordLog);
    }

    @Transactional(rollbackFor = Exception.class)
    public FenRecordLogDto create(FenRecordLog resources) {
        return fenRecordLogMapper.toDto(fenRecordLogRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(FenRecordLog resources) {
        FenRecordLog fenRecordLog = fenRecordLogRepository.findById(resources.getId()).orElseGet(FenRecordLog::new);
        ValidationUtil.isNull(fenRecordLog.getId(), "FenRecordLog", "id", resources.getId());
        fenRecordLog.copy(resources);
        fenRecordLogRepository.save(fenRecordLog);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            fenRecordLogRepository.deleteById(id);
        }
    }

    public void download(List<FenRecordLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FenRecordLogDto fenRecordLog : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户id", fenRecordLog.getUserId());
            map.put("分数分类id", fenRecordLog.getFenId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    //@Transactional
    //访问时新增用户分根据是什么模块的查id
    public synchronized void insertUserFen(String typeName) {
        //log.info("typeName值:{}", typeName);
        if (typeName != null && !typeName.equals("")) {
            Long userId = SecurityUtils.getCurrentUserId();
            //log.info("userId值:{}", userId);
            if (userId != null) {
                List<FenType> list = fenTypeRepository.findByLikeName("%" + typeName + "%");
                //log.info("FenTypeList值:{}", list);
                if (list != null && list.size() == 1) {
                    //TODO 判断上次新增时间和当前时间是否大于1小时 则新增 否则不入库记录
                    List<FenRecordLog> list2 = fenRecordLogRepository.findByFenIdAndUserId(userId, list.get(0).getId());
                    //log.info("FenRecordLog值:{}", list2);
                    if (list2 == null) {
                        //修改该用户的分数
                        int fen = userService.updateFen(userId, list.get(0).getPoint());
                        //log.info("用户分1:{}", fen);
                        //新增用户记录
                        FenRecordLog fenRecordLog = new FenRecordLog();
                        fenRecordLog.setUserId(userId);
                        fenRecordLog.setFenId(list.get(0).getId());
                        fenRecordLogRepository.save(fenRecordLog);
                    } else {
                        if (list2.size() == 0) {
                            //修改该用户的分数
                            int fen = userService.updateFen(userId, list.get(0).getPoint());
                            //log.info("用户分2:{}", fen);
                            //新增用户记录
                            FenRecordLog fenRecordLog = new FenRecordLog();
                            fenRecordLog.setUserId(userId);
                            fenRecordLog.setFenId(list.get(0).getId());
                            fenRecordLogRepository.save(fenRecordLog);
                        } else {
                            //说明有1条记录  比对当前时间是否大于1小时 则入库
                            FenRecordLog fenRecordLog1 = list2.get(0);
                            Timestamp ts1 = fenRecordLog1.getCreateTime();//上一条记录时间
                            Timestamp ts2 = new Timestamp(System.currentTimeMillis());//当前时间
                            // 计算两个时间戳之间的差异（毫秒）
                            long diff = ts2.getTime() - ts1.getTime();
                            // 将差异转换为小时，并与1进行比较
                            if (diff > 60 * 60 * 1000) {
                                //修改该用户的分数
                                int fen = userService.updateFen(userId, list.get(0).getPoint());
                                //log.info("用户分3:{}", fen);
                                //两个时间戳之间的差异大于一个小时
                                //新增用户记录
                                FenRecordLog fenRecordLog = new FenRecordLog();
                                fenRecordLog.setUserId(userId);
                                fenRecordLog.setFenId(list.get(0).getId());
                                fenRecordLogRepository.save(fenRecordLog);
                            }
                        }
                    }
                }
            }
        }
    }
}